package com.brian.mqproducer.service;

import com.alibaba.fastjson.JSONObject;
import com.brian.mqproducer.base.BaseApiService;
import com.brian.mqproducer.base.ResponseBase;
import com.brian.mqproducer.entity.OrderEntity;
import com.brian.mqproducer.mapper.OrderMapper;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.UUID;

/**
 * @program: architect
 * @author: Brian Huang
 * @create: 2019-07-16 22
 **/
@Service
public class OrderService extends BaseApiService implements RabbitTemplate.ConfirmCallback {

    @Resource
    private OrderMapper orderMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Transactional
    public ResponseBase addOrderAndDispatch() {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setName("腾讯云redis单机普通版");
        orderEntity.setOrderCreatetime(new Date());
        // 价格是300元
        orderEntity.setOrderMoney(3000d);
        // 状态为 未支付
        orderEntity.setOrderState(0);
        Long commodityId = 234865434567l;
        // 商品id
        orderEntity.setCommodityId(commodityId);
        String orderId = UUID.randomUUID().toString();
        orderEntity.setOrderId(orderId);

        //1.创建订单  入库
        OrderEntity entity = orderMapper.save(orderEntity);
        if(entity  == null) {
            return setResultError("创建订单失败！！！");
        }

        //2.使用中间件发送到派单队列
        send(orderId);
        return setResultSuccess();
    }

    private void send(String orderId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("orderId", orderId);
        String msg = jsonObject.toString();
        // 封装消息
        Message message = MessageBuilder.withBody(msg.getBytes()).setContentType(MessageProperties.CONTENT_TYPE_JSON)
                .setContentEncoding("utf-8").setMessageId(orderId).build();

        // 构建回调返回的数据（消息id）
        this.rabbitTemplate.setMandatory(true);
        this.rabbitTemplate.setConfirmCallback(this);

        CorrelationData correlationData = new CorrelationData(orderId);
        rabbitTemplate.convertAndSend("order_exchange_name", "orderRoutingKey", message, correlationData);

    }

    // 生产消息确认机制 生产者往服务器端发送消息的时候，采用应答机制
    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        String id = correlationData.getId();
        System.out.println("消息id: " + id);
        if(b){
            System.out.println("消息发送成功！！！");
        }else{
            System.out.println("消息发送失败: " + s);
            //重试发送
            send(id);
        }


    }
}
